package org.flexr.service
{
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.events.ServerSocketConnectEvent;
	import flash.net.ServerSocket;
	import flash.net.Socket;
	
	import mx.controls.Alert;
	
	import org.flexr.events.ServiceEvent;
	import org.flexr.model.Introspect;
	import org.flexr.umvc.CentralDispatcher;
	import org.flexr.umvc.service.AbstractService;
	

	public class SocketService extends AbstractService
	{
		private var socketService:ServerSocket;
		private var address:String = '127.0.0.1';
		private var port:int = 8887;
		private var socket:Socket
	//	private var dispatcher:CentralDispatcher;
		public function SocketService()
		{
    		dispatcher = CentralDispatcher.instance;

			try{
			socketService = new ServerSocket();
			
			socketService.bind(port, address); // Pass in the port number you want to listen on			
			socketService.listen();
           socketService.addEventListener(Event.CONNECT, onConnect);

	 		socketService.addEventListener(Event.ACTIVATE, onActivate);
 
			socketService.addEventListener(ServerSocketConnectEvent.CONNECT, onConnect);

			}
			catch (e:IOError){
			Alert.show(e.message);
			}
			trace(socketService.bound)
 		//	Alert.show('efaef'+ socketService.bound);
 		}
		private function onActivate(e:Event):void
		{

 			socketService.addEventListener(ServerSocketConnectEvent.CONNECT, onConnect);

		}
		private function onConnect(e:ServerSocketConnectEvent):void
		{ 	
			socket = e.socket;
			 //socketService.addEventListener(Event.ACTIVATE, onActivate);

			socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
  		}
		private function onSocketData(e:ProgressEvent):void
		{
  			socket.objectEncoding = 3;
			var s:Boolean =socket.readBoolean() 
  			if(s === false)
  			{
  				dispatcher.dispatchEvent(new ServiceEvent(ServiceEvent.TRACE_DATA, socket.readUTFBytes(socket.bytesAvailable )));
  			}
  			else 
  			{
  				var obj = socket.readObject() ;
  				var objC:Introspect = new Introspect();
  				objC.obj = obj.obj;
  				objC.xml = obj.xml;
   				dispatcher.dispatchEvent(new ServiceEvent(ServiceEvent.OBJECT_DATA, objC));
   			}
  			socket.flush();
		}
		
	}
}